package cn.buttheway.moodmusicdiary.activities;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import cn.buttheway.moodmusicdiary.R;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import cn.buttheway.moodmusicdiary.adapters.MoodHistoryAdapter;
import cn.buttheway.moodmusicdiary.models.MoodEntry;
import cn.buttheway.moodmusicdiary.utils.DatabaseHelper;

public class MainActivity extends AppCompatActivity {

    private Button btnInputMood;
    private TextView tvRecentMoodSummary;
    private RecyclerView rvRecentMoods;
    private Button btnViewFullHistory;

    private DatabaseHelper dbHelper;
    private MoodHistoryAdapter moodAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        setupListeners();
        initDatabase();
        loadRecentMoods();
    }

    private void initViews() {
        btnInputMood = findViewById(R.id.btnInputMood);
        tvRecentMoodSummary = findViewById(R.id.tvRecentMoodSummary);
        rvRecentMoods = findViewById(R.id.rvRecentMoods);
        btnViewFullHistory = findViewById(R.id.btnViewFullHistory);

        rvRecentMoods.setLayoutManager(new LinearLayoutManager(this));
        moodAdapter = new MoodHistoryAdapter();
        rvRecentMoods.setAdapter(moodAdapter);
    }

    private void setupListeners() {
        btnInputMood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, MoodInputActivity.class));
            }
        });

        btnViewFullHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, MoodHistoryActivity.class));
            }
        });
    }

    private void initDatabase() {
        dbHelper = new DatabaseHelper(this);
    }

    private void loadRecentMoods() {
        List<MoodEntry> recentMoods = dbHelper.getRecentMoods(5); // 获取最近5条记录
        moodAdapter.setMoodEntries(recentMoods);
        updateMoodSummary(recentMoods);
    }

    private void updateMoodSummary(List<MoodEntry> recentMoods) {
        if (recentMoods.isEmpty()) {
            tvRecentMoodSummary.setText("还没有心情记录，开始记录你的第一个心情吧！");
        } else {
            // 这里可以添加一些简单的统计，比如最常见的心情
            tvRecentMoodSummary.setText("你最近记录了 " + recentMoods.size() + " 条心情");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadRecentMoods(); // 每次回到主界面时刷新心情记录
    }
}